<!--
  author: tangcheng_cd
  create by: 2018-05-21
  descr: 菜单树组件
-->
<template>
  <div class="menuTreeComp">
    <el-row>
      <slot name="toolbar"></slot>
      <el-input
        size="mini"
        placeholder="搜索菜单内容"
        auto-complete="on"
        class="menu-tree-search-input pull-right"
        v-model="filterText"
      >
        <el-button type="primary" slot="append" icon="el-icon-search"></el-button>
      </el-input>
    </el-row>
    <!--<div class="menu-tree-header">机构树</div>-->
    <div class="menu-tree-header">
      <span style="width:100%" class="clear-fix">
        <span class="el-tree-node__label el-tree-node__label_left">菜单名称
          <!--<el-button size="mini" class="expand-btn" :icon="'el-icon-plus'" @click="expandAll"></el-button>-->
          <!--TODO:这里可以做一个一键展开和一键收缩功能-->
        </span>
      </span>
    </div>
    <el-tree :data="menuData"
             :empty-text="'无菜单数据'"
             :props="defaultProps"
             :default-expand-all="defaultExpandAll"
             :render-content="renderContentFun"
             :filter-node-method="filterNode"
             highlight-current
             @node-click="handleNodeClick"
             show-checkbox
             node-key="id"
             ref="menuTreeRef"
    ></el-tree>
  </div>
</template>

<script type="text/jsx">
  import ajax from '../../../api/ajax/ajax'
  import api from '../../../api/url'
  import {mapGetters} from 'vuex'

  export default {
    name: 'menu-tree',
    props: {
      // 是否默认展开所有的节点
      defaultExpandAll: Boolean
    },
    data () {
      return {
        filterText: '',
        menuData: [],
        defaultProps: {
          children: 'children',
          label: 'name',
          filterText: ''
        },
        checkedMenuArr: []
      }
    },
    computed: {
      ...mapGetters({
        checkedMenuList: 'checkedMenuList'
      })
    },
    watch: {
      filterText (val) {
        this.$refs.menuTreeRef.filter(val)
      },
      // 循环比较 menuId等于obj.id 就添加到数组中
      checkedMenuList (nVal) {
        let menuIdArr = []
        nVal.map(item => {
          menuIdArr.push(item.menuId)
        })
        // nVal.forEach(item => {
        //   this.menuData.forEach(entity => {
        //     if (item.menuId === entity.obj.id) {
        //       this.checkedMenuArr.push(entity)
        //     }
        //   })
        // })
        // 勾选选中项
        // this.$refs.menuTreeRef.setCheckedNodes(this.menuData)
        this.$refs.menuTreeRef.setCheckedKeys(menuIdArr)
        // this.$refs.menuTreeRef.setCheckedNodes(this.checkedMenuArr)
      }
    },
    methods: {
      // 展开所有节点（待实现）
      expandAll () {
        let allNodes = this.$refs.menuTreeRef.store._getAllNodes()
        for (var i = 0; i < allNodes.length; i++) {
          allNodes[i].expanded = false
        }
      },
      // 搜索过滤节点
      filterNode (value, data) {
        if (!value) return true
        return data.obj.name.indexOf(value) !== -1
      },
      // 节点单击处理
      handleNodeClick (data) {
      },
      renderContentFun (h, {data, node, store}) {
        return (
          <span style="width:100%" class="clear-fix">
          <span class="el-tree-node__label el-tree-node__label_left">{ data.obj.name }</span>
        </span>
        )
      },
      // 获取选中的节点（不带父节点）
      getCheckedNodes () {
        return this.$refs.menuTreeRef.getCheckedNodes()
      },
      // 获取菜单数组
      getMenuArray () {
        let menuArray = []
        let treeTransformArray = (menus) => { // 树转数组
          for (let menuItem of menus) {
            menuArray.push(menuItem.obj)
            if (menuItem['children'] && menuItem['children'].length >= 1) {
              treeTransformArray(menuItem.children)
            }
          }
        }
        treeTransformArray(this.menuData)
        return menuArray
      },
      // 获取所有选择的节点（带父节点）
      getCheckedMenuTreeNodes () {
        let nodes = this.$refs.menuTreeRef.getCheckedNodes()
        if (nodes === null || nodes.length === 0) {
          return []
        }

        // 下面干了一件事，将选择节点和选择节点的父节点全部找出来
        let menuArray = this.getMenuArray()
        let resultMap = {}
        let resultNodes = [] // 结果节点组
        let getParentNodes = id => {
          let node = menuArray.find(item => item.id === id)
          if (!node) return
          resultMap[id] = node
          if (node.parentId === 0) {
            return
          }
          getParentNodes(node.parentId)
        }
        for (let node of nodes) {
          let nodeId = node.obj.id
          resultMap[nodeId] = node.obj
          getParentNodes(node.obj.parentId)
        }
        for (let key in resultMap) {
          resultNodes.push(resultMap[key])
        }
        return resultNodes
      },
      // // 清空树的选择
      // resetChecked () {
      //   console.info(this.$refs.menuTreeRef)
      //   this.$refs.menuTreeRef.setCheckedKeys([])
      // }
      // 获取右侧所有菜单的数据
      getMenudate () {
        ajax.post(api.GETMENUTREEBYSYS, {
          sysNo: ''
        }).then(res => {
          this.menuData = this.handleData(res.data)
        }).catch(e => {
          console.info('获取菜单树发生错误！')
        })
      },
      handleData (dataList) {
        let list = dataList.map(item => {
          let insertItem = {
            id: item.obj.id,
            obj: item.obj,
            children: []
          }
          if (item.children) {
            item.children.forEach(data => {
              insertItem.children.push({
                id: data.obj.id,
                obj: data.obj
              })
            })
          }
          return insertItem
        })
        return list
      }
    },
    created () {
      this.getMenudate()
//      模拟测试数据
//    this.menuData = [
//        {
//          id: 'A',
//          obj: {
//            id: 'A',
//            name: 'aaaaaaa'
//          },
//          children: [
//            {
//              obj: {
//                id: 'A11',
//                name: 'aaaaaaa111'
//              }
//            }
//          ]
//        },
//        {
//        id: 'B',
//        obj: {
//            id: 'B',
//            name: 'bbbbbbbbb'
//          }
//        },
//        {
//          id: 'C',
//          obj: {
//            id: 'C',
//            name: 'ccccccccc'
//          }
//        }
//      ]
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .menuTreeComp
    .menu-tree-search-input
      margin-right 10px
      width 200px
    div.menu-tree-header
      font-size 15px
      color #606266
      background-color: #fff
      padding 5px 8px
      text-align left
    .el-tree-node__content
      height 34px
    .expand-btn
      padding 5px 5px

  .el-tree-node__label_left
    float left

  .el-tree-node__label_right
    position relative
    right 8px
    float right

  .clear-fix:after
    content "."
    clear both
    display block
    height 0
    overflow hidden
    visibility hidden
</style>
